package com.novanok.mailtweets;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.novanok.mailtweets.adapter.ListaMensajeDirectoAdapter;
import com.novanok.mailtweets.comun.TwitterUtil;
import com.novanok.mailtweets.entidad.Carpeta;
import com.novanok.mailtweets.entidad.Cuenta;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import twitter4j.DirectMessage;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.User;
import twitter4j.UserList;
import twitter4j.UserStreamListener;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;


public class MyActivity extends Activity {

    private static final String TAG = "MyActivity.java";

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private String[] mPlanetTitles;
    private ActionBarDrawerToggle mDrawerToggle;
    private TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    private static String token;
    private static String tokenSecret;
    private static Map<String, Cuenta> cuentas;
    private static Map<String, Carpeta> carpetas;

    public static ArrayList<DirectMessage> listaMensajes = null;

    public static Map<String, Cuenta> getCuentas() {
        return cuentas;
    }

    public static void setCuentas(Map<String, Cuenta> cuentas) {
        MyActivity.cuentas = cuentas;
    }

    public static Map<String, Carpeta> getCarpetas() {
        return carpetas;
    }

    public static void setCarpetas(Map<String, Carpeta> carpetas) {
        MyActivity.carpetas = carpetas;
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_my );

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        if ( listaMensajes == null )
            listaMensajes = new ArrayList<DirectMessage>();

        if ( cuentas == null )
            cuentas = new HashMap<String, Cuenta>();

        if ( carpetas == null )
            carpetas = new HashMap<String, Carpeta>();

        ( ( ListView ) MyActivity.this.findViewById( R.id.lstPalabras ) ).setAdapter(new ListaMensajeDirectoAdapter(MyActivity.this, listaMensajes));

        mPlanetTitles = getResources().getStringArray( R.array.menu );
        mDrawerLayout = ( DrawerLayout ) findViewById( R.id.drawer_layout );
        mDrawerList = ( ListView ) findViewById( R.id.left_drawer );

        mDrawerLayout.setDrawerShadow( R.drawable.drawer_shadow, GravityCompat.START );
        mDrawerList.setAdapter( new ArrayAdapter<String>( this, R.layout.drawer_list_item, mPlanetTitles ) );
        mDrawerList.setOnItemClickListener( new DrawerItemClickListener() );

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed( View view ) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened( View drawerView ) {
                super.onDrawerOpened( drawerView );
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerLayout.setDrawerListener( mDrawerToggle );
        getActionBar().setDisplayHomeAsUpEnabled( true );
        getActionBar().setHomeButtonEnabled( true );

        twitterStream.setOAuthConsumer( TwitterUtil.getConsumerKey(), TwitterUtil.getConsumerSecret() );
        UserStreamListener listener = new UserStreamListener() {

            @Override
            public void onDeletionNotice(long l, long l2) {

            }

            @Override
            public void onFriendList(long[] longs) {

            }

            @Override
            public void onFavorite(User user, User user2, Status status) {

            }

            @Override
            public void onUnfavorite(User user, User user2, Status status) {

            }

            @Override
            public void onFollow(User user, User user2) {

            }

            @Override
            public void onUnfollow(User user, User user2) {

            }

            @Override
            public void onDirectMessage(DirectMessage directMessage) {
                listaMensajes.add(directMessage);

                MyActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        (( ListaMensajeDirectoAdapter )( ( ListView ) findViewById( R.id.lstPalabras ) ).getAdapter()).notifyDataSetChanged();
                    }
                });
            }

            @Override
            public void onUserListMemberAddition(User user, User user2, UserList userList) {

            }

            @Override
            public void onUserListMemberDeletion(User user, User user2, UserList userList) {

            }

            @Override
            public void onUserListSubscription(User user, User user2, UserList userList) {

            }

            @Override
            public void onUserListUnsubscription(User user, User user2, UserList userList) {

            }

            @Override
            public void onUserListCreation(User user, UserList userList) {

            }

            @Override
            public void onUserListUpdate(User user, UserList userList) {

            }

            @Override
            public void onUserListDeletion(User user, UserList userList) {

            }

            @Override
            public void onUserProfileUpdate(User user) {

            }

            @Override
            public void onBlock(User user, User user2) {

            }

            @Override
            public void onUnblock(User user, User user2) {

            }

            @Override
            public void onStatus(Status status) {

            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

            }

            @Override
            public void onTrackLimitationNotice(int i) {

            }

            @Override
            public void onScrubGeo(long l, long l2) {

            }

            @Override
            public void onStallWarning(StallWarning stallWarning) {

            }

            @Override
            public void onException(Exception e) {

            }
        };

        twitterStream.addListener( listener );

        Uri uri = getIntent().getData();
        String verifier = uri.getQueryParameter( "oauth_verifier" );
        new TwitterGetAccessTokenTask().execute( verifier );
    }


    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        int id = item.getItemId();

        if ( id == R.id.action_settings ) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void iniciar(){
        twitterStream.setOAuthAccessToken( new AccessToken( token, tokenSecret ) );
        twitterStream.user();
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
            selectItem( position );
        }
    }

    private void selectItem( int position ) {
        mDrawerList.setItemChecked( position, true );
        mDrawerLayout.closeDrawer( mDrawerList );

        switch ( position ){
            /// Bandeja Principal
            case 0:{

                break;
            }

            /// Agregar Carpetas
            case 1:{
                Intent i = new Intent( this, ActivityCarpeta.class );
                startActivity(i);
                break;
            }

            /// Agregar Reglas
            case 2:{
                break;
            }

            /// Agregar Cuentas
            case 3:{
                Intent i = new Intent( this, ActivityCuenta.class );
                startActivity(i);
                break;
            }

            /// LogOut
            case 4:{
                break;
            }
        }
    }

    public static String getAccessToken (){
        return token;
    }

    public static String getAccessTokenSecret(){
        return tokenSecret;
    }

    class TwitterGetAccessTokenTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPostExecute( String userName ) {
            iniciar();
        }

        @Override
        protected String doInBackground( String... params ) {

            Twitter twitter = TwitterUtil.getInstance().getTwitter();
            RequestToken requestToken = TwitterUtil.getInstance().getRequestToken();

            try {
                AccessToken accessToken = twitter.getOAuthAccessToken( requestToken, params[0] );
                token = accessToken.getToken();
                tokenSecret = accessToken.getTokenSecret();
            } catch ( TwitterException e ) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
